import {
  Body,
  Controller,
  Get,
  Post,
  Request,
  UseGuards,
} from '@nestjs/common';
import { ApiBearerAuth, ApiTags } from '@nestjs/swagger';
import { UserService } from 'src/user/user.service';
import { AuthService } from './auth.service';
import { InfoResData, InfoResponse } from './dto/info.dto';
import { Types } from 'mongoose';
import {
  LoginRequestBody,
  LoginResFailure,
  LoginResponse,
} from './dto/login.dto';
import {
  RegisterRequestBody,
  RegisterResponse,
  RegisterResponseFail_1,
} from './dto/register.dto';
import { JwtAuthGuard } from './jwt-auth.guard';

@ApiTags('auth')
@Controller('auth')
export class AuthController {
  constructor(
    private readonly authService: AuthService,
    private readonly userService: UserService,
  ) {}

  @Post('login')
  async login(@Body() body: LoginRequestBody) {
    const { username, password } = body;
    const payload = await this.authService.validateUser(username, password);
    if (payload) {
      const token = await this.authService.login(payload);
      return new LoginResponse(token);
    } else {
      return new LoginResFailure();
    }
  }

  @Post('register')
  async register(@Body() body: RegisterRequestBody) {
    const { username, password, nickname } = body;
    try {
      await this.userService.create({
        username,
        password,
        nickname,
      });
    } catch (err) {
      if (err.code === 11000) {
        return new RegisterResponseFail_1();
      }
    }
    return new RegisterResponse();
  }

  @ApiBearerAuth()
  @UseGuards(JwtAuthGuard)
  @Get('info')
  async info(@Request() req) {
    const { id } = req.user;
    const userItem = await this.userService.findOneById(new Types.ObjectId(id));
    const resData: InfoResData = {
      info: {
        id: userItem._id.toHexString(),
        nickname: userItem.info.nickname,
      },
      address_book: userItem.address_book,
      chat_map: userItem.chat_map,
      task_stack: userItem.task_stack,
    };
    return new InfoResponse(resData);
  }
}
